package com;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import com.utils.EncodingDetect;

public class TestReadCsv {
	public static void main(String[] args) throws Exception {
		for(int date = 20230216; date <= 20230216; date++) {
			String path = "D:\\Projects\\工作目录\\版本\\7777-20230215\\"+date+"\\";
			File file = new File(path);
			File[] filenames = file.listFiles();
			int ds6size = 0;
			int noSize = 0;
			System.out.println("测厚日期：" + date);
			Map<String, Integer[]> map = new HashMap<>();
			for(File f : filenames) {
				if(f.getName().startsWith("D")) {
					ds6size++;
					String user = f.getName().substring(0, 3);
					if(!map.containsKey(user)) {
						map.put(user, new Integer[] {0, 0});
					}
					Integer[] cts = map.get(user);
					cts[0] = cts[0] + 1;
					List<String[]> data = readCSV(path+f.getName(), 0, EncodingDetect.getJavaEncode(path+f.getName()));
					if(data != null && data.size() <= 1) {
						noSize++;
						cts[1] = cts[1] + 1;
					}
				}
			}
			System.out.println("总文件数："+ds6size);
			System.out.println("空文件："+noSize);
			System.out.println("总不良率(%)：" + calcRate(noSize, ds6size));
			for(String key : map.keySet()) {
				Integer[] cts = map.get(key);
				System.out.println("机台："+key + " 总文件：" + cts[0] + " 空文件："+cts[1] + " 不良率(%)："+ calcRate(cts[1], cts[0]));
			}
		}
	}
	
	private static String calcRate(Integer integer, Integer integer2) {
		return String.format("%.2f", ((integer * 1.0 / integer2 * 100)));
	}

	@SuppressWarnings("resource")
	public static List<String[]> readCSV(String fileName, int startLine, String gbcode) throws Exception {
		List<String[]> list = new ArrayList<String[]>();
		try {
			DataInputStream in = new DataInputStream(new FileInputStream(new File(fileName)));
			CSVReader csvReader = new CSVReader(new InputStreamReader(in, gbcode), CSVParser.DEFAULT_SEPARATOR,
					CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, startLine);
			String[] strs;
			while ((strs = csvReader.readNext()) != null) {
				list.add(strs);
			}
			csvReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
